# -*- coding: utf-8 -*-
"""
REST API服务
提供查询、配置和管理接口
"""

from flask import Flask, jsonify, request, render_template
from flask_cors import CORS
from datetime import datetime, timedelta
import logging
from typing import Dict, Any

logger = logging.getLogger(__name__)


def create_app(config: Dict[str, Any], db_manager, monitor_engine) -> Flask:
    """创建Flask应用"""
    
    app = Flask(__name__,
                template_folder='../web/templates',
                static_folder='../web/static')
    
    # 启用CORS
    CORS(app)
    
    # 保存引用
    app.config['DB_MANAGER'] = db_manager
    app.config['MONITOR_ENGINE'] = monitor_engine
    app.config['SYSTEM_CONFIG'] = config
    
    # ==================== Web界面路由 ====================
    
    @app.route('/')
    def index():
        """首页 - 监控大屏"""
        return render_template('index.html')
    
    @app.route('/alerts')
    def alerts_page():
        """告警历史页面"""
        return render_template('alerts.html')
    
    @app.route('/config')
    def config_page():
        """配置管理页面"""
        return render_template('config.html')
    
    # ==================== API路由 ====================
    
    @app.route('/api/health', methods=['GET'])
    def health_check():
        """健康检查"""
        db_ok = db_manager.get_session() is not None
        monitor_ok = monitor_engine.running
        
        return jsonify({
            'status': 'healthy' if (db_ok and monitor_ok) else 'unhealthy',
            'database': 'ok' if db_ok else 'error',
            'monitor': 'running' if monitor_ok else 'stopped',
            'timestamp': datetime.now().isoformat()
        })
    
    @app.route('/api/status', methods=['GET'])
    def get_status():
        """获取系统状态"""
        try:
            # 监控引擎状态
            engine_status = monitor_engine.get_status()
            
            # 数据库状态
            db_status = db_manager.get_latest_status()
            
            # 告警统计
            alert_stats = db_manager.get_alert_statistics(days=7)
            
            return jsonify({
                'success': True,
                'data': {
                    'monitor_engine': engine_status,
                    'database_status': db_status,
                    'alert_statistics': alert_stats,
                    'timestamp': datetime.now().isoformat()
                }
            })
        except Exception as e:
            logger.error(f"获取状态失败: {e}", exc_info=True)
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500
    
    @app.route('/api/alerts', methods=['GET'])
    def get_alerts():
        """查询告警历史"""
        try:
            # 解析参数
            limit = request.args.get('limit', 100, type=int)
            offset = request.args.get('offset', 0, type=int)
            alert_level = request.args.get('level')
            database_name = request.args.get('database')
            resolved = request.args.get('resolved', type=bool)
            
            # 时间范围
            start_date = request.args.get('start_date')
            end_date = request.args.get('end_date')
            
            start_time = datetime.fromisoformat(start_date) if start_date else None
            end_time = datetime.fromisoformat(end_date) if end_date else None
            
            # 查询告警
            alerts = db_manager.get_alerts(
                limit=limit,
                offset=offset,
                alert_level=alert_level,
                database_name=database_name,
                start_time=start_time,
                end_time=end_time,
                resolved=resolved
            )
            
            # 总数
            total = db_manager.get_alert_count(
                alert_level=alert_level,
                database_name=database_name,
                start_time=start_time,
                end_time=end_time
            )
            
            return jsonify({
                'success': True,
                'data': {
                    'alerts': [alert.to_dict() for alert in alerts],
                    'total': total,
                    'limit': limit,
                    'offset': offset
                }
            })
        except Exception as e:
            logger.error(f"查询告警失败: {e}", exc_info=True)
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500
    
    @app.route('/api/alerts/<int:alert_id>/resolve', methods=['POST'])
    def resolve_alert(alert_id):
        """标记告警为已解决"""
        try:
            data = request.get_json() or {}
            resolved_by = data.get('resolved_by', 'api')
            
            success = db_manager.resolve_alert(alert_id, resolved_by)
            
            return jsonify({
                'success': success,
                'message': '告警已标记为解决' if success else '告警不存在'
            })
        except Exception as e:
            logger.error(f"标记告警失败: {e}", exc_info=True)
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500
    
    @app.route('/api/alerts/statistics', methods=['GET'])
    def get_alert_statistics():
        """获取告警统计"""
        try:
            days = request.args.get('days', 7, type=int)
            stats = db_manager.get_alert_statistics(days=days)
            
            return jsonify({
                'success': True,
                'data': stats
            })
        except Exception as e:
            logger.error(f"获取统计失败: {e}", exc_info=True)
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500
    
    @app.route('/api/monitor/start', methods=['POST'])
    def start_monitor():
        """启动监控"""
        try:
            monitor_engine.start()
            return jsonify({
                'success': True,
                'message': '监控引擎已启动'
            })
        except Exception as e:
            logger.error(f"启动监控失败: {e}", exc_info=True)
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500
    
    @app.route('/api/monitor/stop', methods=['POST'])
    def stop_monitor():
        """停止监控"""
        try:
            monitor_engine.stop()
            return jsonify({
                'success': True,
                'message': '监控引擎已停止'
            })
        except Exception as e:
            logger.error(f"停止监控失败: {e}", exc_info=True)
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500
    
    @app.route('/api/monitor/check', methods=['POST'])
    def trigger_check():
        """手动触发检查"""
        try:
            if not monitor_engine.running:
                return jsonify({
                    'success': False,
                    'error': '监控引擎未运行'
                }), 400
            
            # 手动触发一次检查
            monitor_engine._run_once()
            
            return jsonify({
                'success': True,
                'message': '检查已触发'
            })
        except Exception as e:
            logger.error(f"触发检查失败: {e}", exc_info=True)
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500
    
    @app.route('/api/config', methods=['GET'])
    def get_config():
        """获取配置"""
        try:
            # 隐藏敏感信息
            safe_config = config.copy()
            if 'mysql' in safe_config:
                safe_config['mysql']['password'] = '******'
            if 'feishu' in safe_config:
                webhook = safe_config['feishu'].get('webhook_url', '')
                if webhook:
                    safe_config['feishu']['webhook_url'] = webhook[:50] + '...'
            
            return jsonify({
                'success': True,
                'data': safe_config
            })
        except Exception as e:
            logger.error(f"获取配置失败: {e}", exc_info=True)
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500
    
    @app.route('/api/export', methods=['GET'])
    def export_alerts():
        """导出告警数据"""
        try:
            # 解析参数
            start_date = request.args.get('start_date')
            end_date = request.args.get('end_date')
            format_type = request.args.get('format', 'json')
            
            start_time = datetime.fromisoformat(start_date) if start_date else \
                        datetime.now() - timedelta(days=30)
            end_time = datetime.fromisoformat(end_date) if end_date else datetime.now()
            
            # 查询数据
            alerts = db_manager.get_alerts(
                limit=10000,
                start_time=start_time,
                end_time=end_time
            )
            
            if format_type == 'csv':
                # TODO: 实现CSV导出
                pass
            
            return jsonify({
                'success': True,
                'data': {
                    'alerts': [alert.to_dict() for alert in alerts],
                    'count': len(alerts),
                    'start_date': start_time.isoformat(),
                    'end_date': end_time.isoformat()
                }
            })
        except Exception as e:
            logger.error(f"导出数据失败: {e}", exc_info=True)
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500
    
    return app

